package com.hex.ds.hdtp.core.inf.data.contrast.service.impl;

import com.hex.ds.hdtp.core.inf.common.utils.JdbcConnectUtil;
import com.hex.ds.hdtp.core.inf.metadata.entity.TableFieldsEntity;
import com.hex.ds.hdtp.core.inf.metadata.po.SourceConfInfoPo;
import com.hex.ds.hdtp.core.inf.metadata.repository.ISourceConfInfoRepository;
import com.hex.ds.hdtp.core.inf.metadata.service.impl.MysqlMethodService;
import com.hex.ds.hdtp.core.inf.metadata.service.impl.SourceMethodHandlerContext;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.sql.SQLException;
import java.util.List;
import java.util.Locale;

@Slf4j
@Service("COMPARE_MYSQL")
public class MysqlInfoService extends AbstractDataInfoService {
    private final MysqlMethodService mysqlMethodService;

    public MysqlInfoService(ISourceConfInfoRepository sourceConfInfoRepository, SourceMethodHandlerContext sourceMethodHandlerContext, MysqlMethodService mysqlMethodService) {
        super(sourceConfInfoRepository, sourceMethodHandlerContext);
        this.mysqlMethodService = mysqlMethodService;
    }

    @Override
    public List<String> selectPartitionField(String sourceCode, String schema, String table) throws SQLException {
        return null;
    }


    @Override
    protected String selectDataNumSql(String schema, String table, String whereSql) {
        return mysqlMethodService.getTableDataNumSql(schema, table, whereSql);
    }


    @Override
    protected String selectCountSumIsNullSql(String schema, String table, String field, String whereSql) {
        if (whereSql != null && whereSql.trim().toUpperCase().startsWith("WHERE")) {
            whereSql = "AND " + whereSql.trim().substring(5);
        }
        return mysqlMethodService.getTableIsNullCountSql(schema, table, field, whereSql);
    }

    /**
     * @Method buildCreateTableSql
     * @Param tableFieldsEntities
     * @Param partitionFieldName
     * @Param isCover
     * @Return java.lang.String
     * @Description 生成建表语句
     * @Author gj.xu
     * @Date 2024/3/8 14:22
     * @Version V2.0
     */
    @Override
    public String buildCreateTableSql(List<TableFieldsEntity> tableFieldsEntities, List<String> partitionFieldName, String isCover) {
        // 库名、表名、字段名默认转小写
        // 是否覆盖建表
        String isDropSql = getIsDropSql(tableFieldsEntities, isCover);
        // 建表SQL头
        String createSqlHeader = mysqlMethodService.getCreateTableHeaderSql(tableFieldsEntities.get(0).getDataBaseName().toLowerCase(Locale.ENGLISH), tableFieldsEntities.get(0).getTableName().toLowerCase(Locale.ENGLISH));
        // 建表SQL体--字段信息
        String createSqlBody = getCreateSqlBody(tableFieldsEntities);
        // 建表SQL--尾括号
        String createSqlFooter = ") \n";
        // 建表SQL--分区字段（不支持分区）
        // 建表SQL--表注释
        String createSqlTableCommon = "COMMENT = '" + tableFieldsEntities.get(0).getTableCommet() + "';";
        return isDropSql + createSqlHeader + createSqlBody + createSqlFooter + createSqlTableCommon;
    }

    private String getCreateSqlBody(List<TableFieldsEntity> tableFieldsEntities) {
        StringBuilder createSqlBody = new StringBuilder();
        for (TableFieldsEntity tableFields : tableFieldsEntities) {
            createSqlBody.append(mysqlMethodService.getCreateTableBodySql(
                    tableFields.getColumnName().toLowerCase(Locale.ENGLISH),
                    tableFields.getColumnType(),
                    (tableFields.getColumnLength() != null && !tableFields.getColumnLength().equals("0")) ? "(" + tableFields.getColumnLength() + ")" : "",
                    tableFields.getColumnCommet() != null ? mysqlMethodService.getCreateColCommentSql(tableFields.getColumnCommet()) : ""));
        }
        return createSqlBody.toString().substring(0, createSqlBody.lastIndexOf(",")).trim();
    }

    private String getIsDropSql(List<TableFieldsEntity> tableFieldsEntities, String isCover) {
        String isDropSql = "";
        if (isCover.equals("1")) {
            isDropSql = mysqlMethodService.getDropTableSql(tableFieldsEntities.get(0).getDataBaseName().toLowerCase(Locale.ENGLISH), tableFieldsEntities.get(0).getTableName().toLowerCase(Locale.ENGLISH));
        }
        return isDropSql;
    }

    /**
     * @Method selectTableExist
     * @Param
     * @Param sourceCode
     * @Param schema
     * @Param table
     * @Return java.lang.Boolean
     * @Description 是否有表
     * @Author xin.zhao
     * @Date 2023/9/1 15:29
     * @Version V1.0
     */
    @Override
    public Boolean selectTableExist(String sourceCode, String schema, String table) throws SQLException {
        List<SourceConfInfoPo> sourceConfInfoPoList = getSourceConfInfoRepository().queryListBySourceCode(sourceCode);
        return JdbcConnectUtil.getTableExist(sourceConfInfoPoList, table.toLowerCase(Locale.ENGLISH));
    }
}
